package com.francis.springbootcommonutil;

import org.apache.commons.codec.binary.Hex;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Random;
import java.util.UUID;

/**
 * <p>Title: StringUtil</p>
 * <p>Description: StringUtil 字符串相关工具类</p>
 * <p>Copyright: Xi An BestTop Technologies, ltd. Copyright(c) 2020/p>
 * @author  ChenWei
 * @version 0.0.1
 * <pre>Histroy:
 *       2020/6/29 16:18 Create by ChenWei
 *</pre>
*/
public class StringUtil extends StringUtils {

    public static void main(String[] args) {
        // 获取32位UUID
        System.out.println(getUUID());
        // 获取当前时间毫秒数（单位：秒）
        System.out.println(getCurrentTimeMillis());
        System.out.println(getMd5Hex(getUUID() + getCurrentTimeMillis() + "bMUpsvzBK8Pq4OoL"));
        System.out.println(getMd5(getUUID() + getCurrentTimeMillis() + "bMUpsvzBK8Pq4OoL"));

        // 获取一个1-5的随机数，比如x
        int randomInteger = getRandomInteger(1,5);
        System.out.println(randomInteger);
        // 获取长度为length 的随机字符串 指定字符串内容：a-z、A-Z或是0-9
        String randomStr = getRandomString(randomInteger);
        System.out.println(randomStr);
        // 密码字符串转 char[]
        char[] chars = getStringArray("111222");
        for(char c : chars){
            System.out.println(c );
        }
        // password = BfYDs + pwd[0] + F + pwd[1] + h + pwd[2] + …… + pwd[5] + x
        String passWord = getNewPassWord(randomStr, chars, randomInteger);
        System.out.println(passWord);
        // base64编码
        System.out.println(getBase64(passWord));
    }

    /**
     * 获取32位UUID
     */
    public static String getUUID() {
        String uuid = UUID.randomUUID().toString().toLowerCase();
        return uuid.replace("-", "");
    }

    /**
     * 获取当前时间毫秒数（单位：秒）
     */
    public static String getCurrentTimeMillis() {
        String currentTimeMillis = String.valueOf(System.currentTimeMillis());
        return currentTimeMillis.substring(0, currentTimeMillis.length() - 3);
    }

    /**
     * md5 加密 32
     * @param str 加密串
     * @return String
     */
    public static String getMd5Hex(String str) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        byte[] digest = md5.digest(str.getBytes());
        return new String(new Hex().encode(digest));
    }

    /**
     * md5 加密 32
     * @param string 加密串
     * @return String
     */
    public static String getMd5(String string) {
        if (isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            StringBuilder result = new StringBuilder();
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result.append(temp);
            }
            return result.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 获取一个1-5的随机数，比如x
     */
    public static int getRandomInteger(int min, int max) {
        Random random = new Random();
        return random.nextInt(max) + min;
    }

    /**
     * 获取长度为length 的随机字符串 指定字符串内容：a-z、A-Z或是0-9
     */
    public static String getRandomString(int length){
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<length;i++){
            // 1:a-z; 2:A-Z; 3:0-9
            int number=random.nextInt(2);
            long result=0;
            switch(number){
                case 0:
                    result=Math.round(Math.random()*25+65);
                    sb.append(String.valueOf((char)result));
                    break;
                case 1:
                    result=Math.round(Math.random()*25+97);
                    sb.append(String.valueOf((char)result));
                    break;
                case 2:
                    sb.append(String.valueOf(new Random().nextInt(10)));
                    break;
            }
        }
        return sb.toString();
    }

    /**
     * 将密码明文拆成字符数组，比如密码是123456，则拆为 pwd = [1,2,3,4,5,6]
    */
    public static char[] getStringArray(String str){
       return str.toCharArray();
    }

    /**
     * password = BfYDs + pwd[0] + F + pwd[1] + h + pwd[2] + …… + pwd[5] + x
     * 随机字符串str，后面将密码拼接，且隔位插入随机字符串
     */
    public static String getNewPassWord(String randomStr, char[] pwd, int x){
        StringBuffer sb = new StringBuffer();
        sb.append(randomStr);
        for(int i = 0; i < pwd.length; i ++ ){
            char c = pwd[i];
           sb.append(c);
           if(pwd.length-1 >i ){
               sb.append(getRandomString(1));
           }
        }
        sb.append(x);
        return sb.toString();
    }

    /**
     * base64编码
     */
    public static String getBase64(String str ){
        try {
//            return  Base64.getEncoder().encodeToString(str.getBytes("utf-8"));
            return  Base64.getMimeEncoder().encodeToString(str.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return str;
        }
    }

}
